<template>
  <div class="user-editor">
    <el-card v-if="model" shadow="never">
      <template #header>
        <div class="header">
          <span>用户详情与编辑</span>
          <el-tag type="info" v-if="model.id">ID: {{ model.id }}</el-tag>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="model"
        :rules="rules"
        label-width="96px"
        class="form-grid"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="model.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="model.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="model.phone" placeholder="可选" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="model.gender" placeholder="选择性别" clearable>
            <el-option label="男" value="M" />
            <el-option label="女" value="F" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="model.age" :min="0" :max="150" />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="model.role">
            <el-option label="用户" value="USER" />
            <el-option label="咨询师" value="COUNSELOR" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="model.status" placeholder="请选择状态">
            <el-option
              v-for="opt in statusOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="余额" prop="account_balance">
          <el-input-number v-model="model.account_balance" :step="1" :min="0" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-input v-model="model.avatar" placeholder="头像 URL" />
        </el-form-item>

        <el-form-item label="生日" prop="brith_date">
          <el-date-picker v-model="model.brith_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>

          <!-- 新增：权限开关 -->
          <el-form-item label="允许评论">
            <el-switch v-model="model.allowComment" active-text="是" inactive-text="否" />
          </el-form-item>

          <el-form-item label="允许发送文章">
            <el-switch v-model="model.allowPost" active-text="是" inactive-text="否" />
          </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="onSubmit">保存修改</el-button>
          <el-button :disabled="submitting" @click="onReset">重置修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-empty v-else description="暂无用户数据，请先搜索" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { User } from '@/types/User'

const props = defineProps<{
  user: User | null
}>()

const emits = defineEmits<{
  (e: 'submit', payload: Partial<User>): void
}>()

// 可编辑模型：基于 props.user 拷贝
type AdminUserEdit = Partial<User> & {
  allowComment?: boolean
  allowPost?: boolean
}

const model = ref<AdminUserEdit | null>(null)

watch(
  () => props.user,
  (val) => {
    model.value = val ? ({ ...(val as any) } as AdminUserEdit) : null
    // 若后端状态存在，则进行规范化（大小写/数字映射）；未知值不强制为默认
    if (model.value && (model.value as any).status != null) {
      const normalized = normalizeStatus((model.value as any).status)
      if (normalized) (model.value as any).status = normalized
    }
    // 默认布尔开关
    if (model.value) {
      if (typeof model.value.allowComment === 'undefined') model.value.allowComment = false
      if (typeof model.value.allowPost === 'undefined') model.value.allowPost = false
    }
  },
  { immediate: true }
)

const formRef = ref<FormInstance>()
const submitting = ref(false)

const emailRe = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
const rules = computed<FormRules>(() => ({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: (_r: any, v: string, cb: any) => cb(emailRe.test(v) ? undefined : new Error('邮箱格式不正确')), trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}))

// 状态值与中文标签映射 + 下拉选项
const STATUS_LABELS: Record<NonNullable<User['status']>, string> = {
  ACTIVE: '正常',
  INACTIVE: '未激活',
  BANNED: '封禁',
}
const statusOptions = [
  { label: STATUS_LABELS.ACTIVE, value: 'ACTIVE' as const },
  { label: STATUS_LABELS.INACTIVE, value: 'INACTIVE' as const },
  { label: STATUS_LABELS.BANNED, value: 'BANNED' as const },
]

// 规范化后端可能返回的状态（大小写/数值）
function normalizeStatus(v: any): User['status'] | null {
  if (v == null) return null
  const key = String(v).trim().toUpperCase()
  if (key === 'ACTIVE' || key === '1') return 'ACTIVE'
  if (key === 'INACTIVE' || key === '0') return 'INACTIVE'
  if (key === 'BANNED' || key === '2') return 'BANNED'
  return null
}

async function onSubmit() {
  if (!model.value) return
  try {
    submitting.value = true
    await formRef.value?.validate()
    emits('submit', model.value)
  } catch (e) {
    // 已由表单显示
  } finally {
    submitting.value = false
  }
}

function onReset() {
  model.value = props.user ? ({ ...(props.user as any) } as AdminUserEdit) : null
  if (model.value) {
    if (typeof model.value.allowComment === 'undefined') model.value.allowComment = false
    if (typeof model.value.allowPost === 'undefined') model.value.allowPost = false
  }
}
</script>

<style scoped>
.user-editor {
  margin-top: 16px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px 16px;
}
.form-grid :deep(.el-form-item) {
  margin-bottom: 12px;
}
@media (max-width: 640px) {
  .form-grid { grid-template-columns: 1fr; }
}
</style>
